package com.htfyun.factorytest.engineer_test;

import android.widget.RadioButton;
import android.widget.RadioGroup;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentTransaction;

import java.util.List;

public class FragmentTabAdapter implements RadioGroup.OnCheckedChangeListener {
    private int currentTab;
    private final FragmentActivity fragmentActivity;
    private final int fragmentContentId;
    private final List<Fragment> fragments;

    public FragmentTabAdapter(FragmentActivity fragmentActivity2, List<Fragment> list, int contentId, RadioGroup radioGroup) {
        fragments = list;
        fragmentActivity = fragmentActivity2;
        fragmentContentId = contentId;
        FragmentTransaction beginTransaction = fragmentActivity2.getSupportFragmentManager().beginTransaction();
        beginTransaction.add(contentId, list.get(0));
        beginTransaction.commit();
        ((RadioButton) radioGroup.getChildAt(0)).setChecked(true);
        radioGroup.setOnCheckedChangeListener(this);
    }

    public void onCheckedChanged(RadioGroup radioGroup, int id) {
        for (int i = 0; i < radioGroup.getChildCount(); i++) {
            FragmentTransaction beginTransaction = fragmentActivity.getSupportFragmentManager().beginTransaction();
            Fragment fragment = fragments.get(i);
            beginTransaction.hide(fragment);
            if (radioGroup.getChildAt(i).getId() == id) {
                getCurrentFragment().onPause();
                if (fragment.isAdded()) {
                    fragment.onResume();
                } else {
                    beginTransaction.add(fragmentContentId, fragment);
                }
                beginTransaction.show(fragment);
                currentTab = i;
            }
            beginTransaction.commit();
        }
    }

    private Fragment getCurrentFragment() {
        return fragments.get(currentTab);
    }

}
